/**
 * 
 */
package com.yidu.drug.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yidu.drug.action.vo.FdSellDetailModelVo;
import com.yidu.drug.common.Message;
import com.yidu.drug.common.Page;
import com.yidu.drug.common.Tools;
import com.yidu.drug.model.DrugManagerModel;
import com.yidu.drug.model.FdSellDetailModel;
import com.yidu.drug.model.FdSellModel;
import com.yidu.drug.model.FinancialRecordModel;
import com.yidu.drug.model.InventoryRecordModel;
import com.yidu.drug.model.RepertoryModel;
import com.yidu.drug.service.FdSellDetailService;
import com.yidu.drug.service.FdSellService;
import com.yidu.drug.service.FinancialRecordService;
import com.yidu.drug.service.FinancialSheetsService;
import com.yidu.drug.service.InventoryRecordService;
import com.yidu.drug.service.InventoryService;
import com.yidu.drug.service.MemberService;
import com.yidu.drug.service.RepertoryService;

/**
 * @author meilina
 * 2018年8月15日上午10:23:03
 * @version 1.0
 */
@Controller
@RequestMapping("/fdSell")
public class FdSellAction {
	//销售表service
	@Resource
	private FdSellService fdService;
	
	//会员表service
	@Resource
	private MemberService memberService;
	
	//销售详情表service
	@Resource
	private FdSellDetailService fdSellDetailService;
	
	//财务表service
	@Resource
	private FinancialSheetsService financialSheetsService;
	
	//财务记录表service
	@Resource
	private FinancialRecordService financialRecordService;
	
	//库存详情表service
	@Resource
	private InventoryService inventoryService;
	
	//库存表service
	@Resource
	private RepertoryService repertoryService;
	
	//库存记录表service
	@Resource
	private InventoryRecordService inventoryRecordService;
	
	/**
	 * 查询所有和条件查询分页
	 * @param response 响应
	 * @param me 会员对象
	 * @param page 页数
	 * @param limit 行数
	 * @return
	 */
	@RequestMapping("/findAllFdSell")
	@ResponseBody
	public Map<String, Object> findAllFdSell(HttpSession session,HttpServletResponse response,FdSellModel fdSellModel,int page,int limit,String dateOne,String dateTwo){
		//取到session对象
		DrugManagerModel manager = (DrugManagerModel) session.getAttribute("manager");
		System.out.println("进来啦++++++++++++++++++++++++++++++");
		System.out.println(fdSellModel.getSellName()+"======================");
		response.setCharacterEncoding("UTF-8");
		Page pages = new Page();
		pages.setPage(page);
		pages.setRows(limit);
		Map<String,String> map=new HashMap<>();
		map.put("sellName", fdSellModel.getSellName());
		//map.put("filId",manager.getFilId());
		DrugManagerModel fd = (DrugManagerModel) session.getAttribute("manager");
		map.put("filId", fd.getFilId());
		map.put("start", String.valueOf(pages.getStart()));
		map.put("rows", String.valueOf(pages.getRows()));
		if(!Tools.isEmpty(dateOne)&&!Tools.isEmpty(dateTwo)){
			if(dateOne.compareTo(dateTwo)>0){
				map.put("dateOne", dateTwo);
				map.put("dateTwo", dateOne);
			}else{
				map.put("dateOne", dateOne);
				map.put("dateTwo", dateTwo);
			}
		}else if(!Tools.isEmpty(dateOne)&&Tools.isEmpty(dateTwo)){
			map.put("dateOne", dateOne);
		}else if(!Tools.isEmpty(dateTwo)&&Tools.isEmpty(dateOne)){
			map.put("dateTwo", dateTwo);
		}
		List<FdSellModel> list=fdService.findAllPage(map);
		for (int i = 0; i < list.size(); i++) {
			List<FdSellDetailModel> fdList = fdSellDetailService.findBySellId(list.get(i).getSellId());
			if(!Tools.isEmpty(fdList)){
				for(int j = 0;j<fdList.size();j++){
					System.out.println("-----退货数量"+fdList.get(j).getYthNumber());
					if(fdList.size()==1){
						if(fdList.get(j).getYthNumber()!=null){
							list.get(i).setTuihuo("0");
							
						}else{
							list.get(i).setTuihuo("1");
						}
					}else{
						if(fdList.get(j).getYthNumber()!=null){
							list.get(i).setTuihuo("0");
							break;
							
						}else{
							list.get(i).setTuihuo("1");
						}
					}
					
					
				}
			}
		}
		
		Map<String, Object> maps = new HashMap<>();
		//需要符合layUI格式，code msg count data
		maps.put("code", 0);
		maps.put("msg", "1");
		maps.put("count", fdService.findAllPageRows(map));
		maps.put("data", list);
		fdSellModel=new FdSellModel();
		
		return maps;
	}
	
	/*
	 *分页查询.加条件查询--yuanwei
	 */
	@RequestMapping("/findAllPage")
	@ResponseBody
	public Map<String, Object> findAllPage(HttpSession session,HttpServletResponse response,FdSellModel fdSellModel,int page,int limit,String dateOne,String dateTwo){
		//取到session对象
		DrugManagerModel manager = (DrugManagerModel) session.getAttribute("manager");
		System.out.println("进来啦++++++++++++++++++++++++++++++");
		System.out.println(fdSellModel.getSellName()+"======================");
		response.setCharacterEncoding("UTF-8");
		Page pages = new Page();
		pages.setPage(page);
		pages.setRows(limit);
		Map<String,String> map=new HashMap<>();
		map.put("sellName", fdSellModel.getSellName());
		//map.put("filId",manager.getFilId());
		map.put("filId",manager.getFilId());
		map.put("start", String.valueOf(pages.getStart()));
		map.put("rows", String.valueOf(pages.getRows()));
		if(!Tools.isEmpty(dateOne)&&!Tools.isEmpty(dateTwo)){
			if(dateOne.compareTo(dateTwo)>0){
				map.put("dateOne", dateTwo);
				map.put("dateTwo", dateOne);
			}else{
				map.put("dateOne", dateOne);
				map.put("dateTwo", dateTwo);
			}
		}else if(!Tools.isEmpty(dateOne)&&Tools.isEmpty(dateTwo)){
			map.put("dateOne", dateOne);
		}else if(!Tools.isEmpty(dateTwo)&&Tools.isEmpty(dateOne)){
			map.put("dateTwo", dateTwo);
		}
		List<FdSellModel> list=fdService.findAllPage(map);
		Map<String, Object> maps = new HashMap<>();
		//需要符合layUI格式，code msg count data
		maps.put("code", 0);
		maps.put("msg", "1");
		maps.put("count", fdService.findAllPageRows(map));
		maps.put("data", list);
		fdSellModel=new FdSellModel();
		
		return maps;
	}
	
	@RequestMapping("/sjhm")
	@ResponseBody
	public Integer findAllid(String memberPhone){
		Integer rows=memberService.sjhm(Long.valueOf(memberPhone));
		return rows;
		
	}
	//得到金额
	@RequestMapping("/jes")
	@ResponseBody
	public Double jes(String arr){
		Gson gosn=new Gson();
		//创建一个提示消息的对象
		Message msg = new Message();
		//使用Type类，取得相应类型对象的class属性
		java.lang.reflect.Type listType=new TypeToken<ArrayList<FdSellDetailModelVo>>(){}.getType();//TypeToken内的泛型就是Json数据中的类型
		//使用集合接受将json转换为java对象集合后的数据
		ArrayList<FdSellDetailModelVo> list = gosn.fromJson(arr, listType);
		Double shje = 0.00;
		for (int i=0;i<list.size();i++) {
			shje+=Double.valueOf(list.get(i).getMxMoney());
		}
		return shje;
		
	}
	
	//会员付款
	@RequestMapping("/adds")
	@ResponseBody
	public int adds(HttpSession session,String arr,FdSellDetailModel fdSellDetailModel,FdSellModel fdSellModel,InventoryRecordModel inventoryRecordModel,FinancialRecordModel financialRecordModel,String memberPhone,String jinr) throws UnsupportedEncodingException{
		//销售表id
		String sellId="xs_"+Tools.getDateOrderNo();
		//销售时间
		Timestamp t = new Timestamp(new Date().getTime());
		//流水号
		String serNumber=Tools.getDateOrderNumber();
		//根据手机号码查询会员id
		String memberId=memberService.findsjById(Long.valueOf(memberPhone));
		
		//取到session对象
		DrugManagerModel manager = (DrugManagerModel) session.getAttribute("manager");
		//分公司id
		String filId=manager.getFilId();
		//根据分公司id查询库存表的id
		//String repId=repertoryService.findById(filId);
		
		//订单详情表数据
		Gson gosn=new Gson();
		//创建一个提示消息的对象
		Message msg = new Message();
		//使用Type类，取得相应类型对象的class属性
		java.lang.reflect.Type listType=new TypeToken<ArrayList<FdSellDetailModelVo>>(){}.getType();//TypeToken内的泛型就是Json数据中的类型
		//使用集合接受将json转换为java对象集合后的数据
		ArrayList<FdSellDetailModelVo> list = gosn.fromJson(arr, listType);
		Double ysje = 0.00;
		Double shje=0.00;
		Integer sl=0;
		for (int i=0;i<list.size();i++) {
			System.out.println(list.get(i).getDrugId()+"药品id============");
			System.out.println(list.get(i).getNumbers()+"条形码===========");
			String drugName=new String(list.get(i).getDrugName().getBytes("ISO8859-1"),"UTF-8");
			System.out.println(drugName+"药品名字==========");
			System.out.println(Double.valueOf(list.get(i).getMxDiscountRate())+"折扣率==========");
			System.out.println(list.get(i).getMxQuantity()+"数量==============");
			System.out.println(list.get(i).getMxMoney()+"实收金额============");
			System.out.println(list.get(i).getMxMoneys()+"应收金额========");
			System.out.println(list.get(i).getMxPrice()+"零售价========");
			System.out.println(list.get(i).getMxPrices()+"折扣后单价===============");
			sl+=list.get(i).getMxQuantity();
			ysje+=Double.valueOf(list.get(i).getMxMoneys());
			shje+=Double.valueOf(list.get(i).getMxMoney());
			
			//根据分公司id和业务id查询库存表的id
			String repId=repertoryService.findByFilIdPwId(list.get(i).getDrugId(), filId);
			
			//根据库存id和批次号以及药品id查询药品数量
			Integer kcsl=inventoryService.kcsl(list.get(i).getDrugId(), list.get(i).getNumbers(), repId);
			
			if(kcsl>list.get(i).getMxQuantity()){
				//根据药品id和批次号和库存id修改库存表的数量 
				inventoryService.updates(kcsl-list.get(i).getMxQuantity(), list.get(i).getDrugId(), list.get(i).getNumbers(), repId);
				RepertoryModel reper=repertoryService.selectByPrimaryKey(repId);
				//根据计算得到总数量
				reper.setRepNumber(reper.getRepNumber()-list.get(i).getMxQuantity());
				//修改总数量
				repertoryService.updateByPrimaryKeySelective(reper);
			}
			
			
			//销量详情表id
			String mxId="xsxq_"+Tools.getDateOrderNo();
			//加入销量详情id
			fdSellDetailModel.setMxId(mxId);
			//销量表id
			fdSellDetailModel.setSellId(sellId);
			//药品id
			fdSellDetailModel.setDrugId(list.get(i).getDrugId());
			//条形编码
			fdSellDetailModel.setMxNumber(Long.valueOf(list.get(i).getNumbers()));
			//折扣率
			fdSellDetailModel.setMxDiscountRate(new BigDecimal(list.get(i).getMxDiscountRate()));
			//数量
			fdSellDetailModel.setMxQuantity(Long.valueOf(list.get(i).getMxQuantity()));
			//实收金额
			fdSellDetailModel.setMxMoney(new BigDecimal(list.get(i).getMxMoney()));
			//应收金额
			fdSellDetailModel.setMxMoneys(new BigDecimal(list.get(i).getMxMoneys()));
			//零售价
			fdSellDetailModel.setMxPrice(new BigDecimal(list.get(i).getMxPrice()));
			//折扣后单价
			fdSellDetailModel.setMxPrices(new BigDecimal(list.get(i).getMxPrices()));
			fdSellDetailService.insertSelective(fdSellDetailModel);
			
			//设置一个库存记录id
			String irId="kcjl_"+Tools.getDateOrderNo();
			//库存记录表id
			inventoryRecordModel.setIrId(irId);
			//库存记录业务id
			inventoryRecordModel.setPwId(list.get(i).getDrugId());
			//材料名称
			inventoryRecordModel.setMatName(drugName);
			//材料数量
			inventoryRecordModel.setMatNum(list.get(i).getMxQuantity());
			//得到当前时间
			Timestamp date = new Timestamp(new Date().getTime());
			//记录时间
			inventoryRecordModel.setIrTime(date);
			//记录类型
			inventoryRecordModel.setIrType("零售");
			//操作人
			inventoryRecordModel.setOperator(manager.getManUser());
			//是否有效
			inventoryRecordModel.setIsva("有效");
			//分公司ID
			inventoryRecordModel.setFilId(filId);
			//批次号
			inventoryRecordModel.setNumbers(list.get(i).getNumbers());
			inventoryRecordService.insertSelective(inventoryRecordModel);
		}
		//折扣
		Double zk=ysje-shje;
		
		//根据分公司id查询金额
		Double jine=financialSheetsService.findSumMoney(filId);
		//根据分公司id修改金额 
		financialSheetsService.updates(new BigDecimal(jine+shje), filId);
		//根据分公司id查询财务表id
		String fsId=financialSheetsService.findByIds(filId);
		
		//销售表id
		fdSellModel.setSellId(sellId);
		fdSellModel.setMemberId(memberId);
		//销售人名字
		fdSellModel.setSellName(manager.getManUser());
		//销售时间
		fdSellModel.setSellDate(t);
		//销售应收金额
		fdSellModel.setSellTotalMoney(new BigDecimal(ysje));
		//销售的数量
		fdSellModel.setSellTotalNumber(Long.valueOf(sl));
		//流水号
		fdSellModel.setSerNumber(Long.valueOf(serNumber));
		//实际收款
		fdSellModel.setSellMoney(new BigDecimal(shje));
		//折扣
		fdSellModel.setSellDiscount(new BigDecimal(zk));
		//分公司id
		fdSellModel.setFilId(filId);
		//找零
		fdSellModel.setSellChange(new BigDecimal(Integer.valueOf(jinr)-shje));
		//加入
		fdService.insertSelective(fdSellModel);
		
		//生成一个财务记录ID
		String frId="cwjl_"+Tools.getDateOrderNo();
		//财务记录ID
		financialRecordModel.setFrId(frId);
		//财务ID
		financialRecordModel.setFsId(fsId);
		//业务ID
		financialRecordModel.setPwId(sellId);
		//财务记录名称
		financialRecordModel.setFrName("零售");
		//财务记录总金额
		financialRecordModel.setFrSumprice(new BigDecimal(jine+shje));
		//财务记录进出帐
		financialRecordModel.setFrPrice(new BigDecimal(shje));
		//得到当前时间
		Timestamp dates = new Timestamp(new Date().getTime());
		//财务记录时间
		financialRecordModel.setFrTime(dates);
		//是否有效
		financialRecordModel.setIsva("有效");
		//财务记录加入
		int rows =financialRecordService.insertSelective(financialRecordModel);
		
		return rows;
		
	}
	//得到金额
	@RequestMapping("/je")
	@ResponseBody
	public Double je(String arr){
		Gson gosn=new Gson();
		//创建一个提示消息的对象
		Message msg = new Message();
		//使用Type类，取得相应类型对象的class属性
		java.lang.reflect.Type listType=new TypeToken<ArrayList<FdSellDetailModelVo>>(){}.getType();//TypeToken内的泛型就是Json数据中的类型
		//使用集合接受将json转换为java对象集合后的数据
		ArrayList<FdSellDetailModelVo> list = gosn.fromJson(arr, listType);
		Double ysje = 0.00;
		for (int i=0;i<list.size();i++) {
			ysje+=Double.valueOf(list.get(i).getMxMoneys());
		}
		return ysje;
		
	}
	
	//普通付款
	@RequestMapping("/ptfkuan")
	@ResponseBody
	public int ptfkuan(HttpSession session,String arr,FdSellDetailModel fdSellDetailModel,FdSellModel fdSellModel,InventoryRecordModel inventoryRecordModel,FinancialRecordModel financialRecordModel,String jinr) throws UnsupportedEncodingException{
		//销售表id
		String sellId="xs"+Tools.getDateOrderNo();
		//销售时间
		Timestamp t = new Timestamp(new Date().getTime());
		//流水号
		String serNumber=Tools.getDateOrderNumber();
		
		//取到session对象
		DrugManagerModel manager = (DrugManagerModel) session.getAttribute("manager");
		//分公司id
		String filId=manager.getFilId();
		//根据分公司id查询库存表的id
		//String repId=repertoryService.findById(filId);
		
		//订单详情表数据
		Gson gosn=new Gson();
		//创建一个提示消息的对象
		Message msg = new Message();
		//使用Type类，取得相应类型对象的class属性
		java.lang.reflect.Type listType=new TypeToken<ArrayList<FdSellDetailModelVo>>(){}.getType();//TypeToken内的泛型就是Json数据中的类型
		//使用集合接受将json转换为java对象集合后的数据
		ArrayList<FdSellDetailModelVo> list = gosn.fromJson(arr, listType);
		Double ysje = 0.00;
		Integer sl=0;
		for (int i=0;i<list.size();i++) {
			System.out.println(list.get(i).getDrugId()+"药品id============");
			String drugName=new String(list.get(i).getDrugName().getBytes("ISO8859-1"),"UTF-8");
			sl+=list.get(i).getMxQuantity();
			ysje+=Double.valueOf(list.get(i).getMxMoneys());
			
			//根据分公司id和业务id查询库存表的id
			String repId=repertoryService.findByFilIdPwId(list.get(i).getDrugId(), filId);
			//根据库存id和批次号以及药品id查询药品数量
			Integer kcsl=inventoryService.kcsl(list.get(i).getDrugId(), list.get(i).getNumbers(), repId);
			
			if(kcsl>list.get(i).getMxQuantity()){
				//根据药品id和批次号和库存id修改库存表的数量 
				inventoryService.updates(kcsl-list.get(i).getMxQuantity(), list.get(i).getDrugId(), list.get(i).getNumbers(), repId);
				RepertoryModel reper=repertoryService.selectByPrimaryKey(repId);
				//根据计算得到总数量
				reper.setRepNumber(reper.getRepNumber()-list.get(i).getMxQuantity());
				//修改总数量
				repertoryService.updateByPrimaryKeySelective(reper);
			}
			//销量详情表id
			String mxId="xsxq_"+Tools.getDateOrderNo();
			//加入销量详情id
			fdSellDetailModel.setMxId(mxId);
			//销量表id
			fdSellDetailModel.setSellId(sellId);
			//药品id
			fdSellDetailModel.setDrugId(list.get(i).getDrugId());
			//条形编码
			fdSellDetailModel.setMxNumber(Long.valueOf(list.get(i).getNumbers()));
			//折扣率
			fdSellDetailModel.setMxDiscountRate(new BigDecimal(0));
			//数量
			fdSellDetailModel.setMxQuantity(Long.valueOf(list.get(i).getMxQuantity()));
			//实收金额
			fdSellDetailModel.setMxMoney(new BigDecimal(list.get(i).getMxMoneys()));
			//应收金额
			fdSellDetailModel.setMxMoneys(new BigDecimal(list.get(i).getMxMoneys()));
			//零售价
			fdSellDetailModel.setMxPrice(new BigDecimal(list.get(i).getMxPrice()));
			//折扣后单价
			fdSellDetailModel.setMxPrices(new BigDecimal(list.get(i).getMxPrice()));
			fdSellDetailService.insertSelective(fdSellDetailModel);
			
			//设置一个库存记录id
			String irId="kcjl_"+Tools.getDateOrderNo();
			//库存记录表id
			inventoryRecordModel.setIrId(irId);
			//库存记录业务id
			inventoryRecordModel.setPwId(list.get(i).getDrugId());
			//材料名称
			inventoryRecordModel.setMatName(drugName);
			//材料数量
			inventoryRecordModel.setMatNum(list.get(i).getMxQuantity());
			//得到当前时间
			Timestamp date = new Timestamp(new Date().getTime());
			//记录时间
			inventoryRecordModel.setIrTime(date);
			//记录类型
			inventoryRecordModel.setIrType("零售");
			//操作人
			inventoryRecordModel.setOperator(manager.getManUser());
			//是否有效
			inventoryRecordModel.setIsva("有效");
			//分公司ID
			inventoryRecordModel.setFilId(filId);
			//批次号
			inventoryRecordModel.setNumbers(list.get(i).getNumbers());
			inventoryRecordService.insertSelective(inventoryRecordModel);
		}
		
		//根据库存表id查询库存详情表的所有数量
		//Integer kucsl=inventoryService.findAllsl(repId);
		//根据分公司id修改库存表数量
		//repertoryService.updates(Long.valueOf(kucsl), filId);
		
		//根据分公司id查询金额
		Double jine=financialSheetsService.findSumMoney(filId);
		//根据分公司id修改金额 
		financialSheetsService.updates(new BigDecimal(jine+ysje), filId);
		//根据分公司id查询财务表id
		String fsId=financialSheetsService.findByIds(filId);
		
		//销售表id
		fdSellModel.setSellId(sellId);
		
		//销售人名字
		fdSellModel.setSellName(manager.getManUser());
		//销售时间
		fdSellModel.setSellDate(t);
		//销售应收金额
		fdSellModel.setSellTotalMoney(new BigDecimal(ysje));
		//销售的数量
		fdSellModel.setSellTotalNumber(Long.valueOf(sl));
		//流水号
		fdSellModel.setSerNumber(Long.valueOf(serNumber));
		//实际收款
		fdSellModel.setSellMoney(new BigDecimal(ysje));
		//折扣
		fdSellModel.setSellDiscount(new BigDecimal(0));
		//分公司id
		fdSellModel.setFilId(filId);
		//找零
		fdSellModel.setSellChange(new BigDecimal(Integer.valueOf(jinr)-ysje));
		fdService.insertSelective(fdSellModel);
		
		
		//生成一个财务记录ID
		String frId="cwjl_"+Tools.getDateOrderNo();
		//财务记录ID
		financialRecordModel.setFrId(frId);
		//财务ID
		financialRecordModel.setFsId(fsId);
		//业务ID
		financialRecordModel.setPwId(sellId);
		//财务记录名称
		financialRecordModel.setFrName("零售");
		//财务记录总金额
		financialRecordModel.setFrSumprice(new BigDecimal(jine+ysje));
		//财务记录进出帐
		financialRecordModel.setFrPrice(new BigDecimal(ysje));
		//得到当前时间
		Timestamp dates = new Timestamp(new Date().getTime());
		//财务记录时间
		financialRecordModel.setFrTime(dates);
		//是否有效
		financialRecordModel.setIsva("有效");
		//财务记录加入
		int rows =financialRecordService.insertSelective(financialRecordModel);
		return rows;
	}
}